package com.bsj.power.pls.config.mq;

import com.alibaba.fastjson.JSON;
import com.bsj.power.common.config.rocketmq.constant.ConsumerGroupConstant;
import com.bsj.power.common.constant.MqTopicAndTagConstants;
import com.bsj.power.common.def.entity.alarmReport.AlarmReport;
import com.bsj.power.common.def.mq.sdk.face.PersonInfo;
import com.bsj.power.common.util.ExceptionUtil;
import com.bsj.power.pls.queue.service.impl.QueueComposeAlarmImpl;
import com.bsj.power.pls.queue.service.impl.QueueHumanFaceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author LiJiaXin
 * @version 1.0.0
 * @description MqttPlsRocketmqConsumer
 * @time 2024/4/18 15:15
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = MqTopicAndTagConstants.BASE_SERVER_PLS_CHANGE_TOPIC,
        consumerGroup = ConsumerGroupConstant.TRAVEL_MQTT_PLS_DOWN_MSG_GROUP,
        selectorExpression = MqTopicAndTagConstants.BASE_CHANGE_PLS_UPDATE_TAG,
        messageModel = MessageModel.CLUSTERING)
public class MqttPlsRocketmqConsumer implements RocketMQListener<MessageExt>, RocketMQPushConsumerLifecycleListener {

    @Autowired
    private QueueComposeAlarmImpl queueComposeAlarm;

    @Autowired
    private QueueHumanFaceImpl queueHumanFace;

    @Async("powerPlsAsync")
    @Override
    public void onMessage(MessageExt messageExt) {
        String message = new String(messageExt.getBody());
        String tags = messageExt.getTags();
        log.info("PLS系统MQ消息,tag: {}, msg: {}", tags, message);
        try {
            queueComposeAlarm.doRun(JSON.parseObject(message, AlarmReport.class));
        } catch (Exception e) {
            log.error("PLS系统MQ数据消费-->消费失败，失败原因： {}", ExceptionUtil.getStackStr(e));
        }
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        // 设置消费者消息重试次数
        defaultMQPushConsumer.setMaxReconsumeTimes(3);
        //设置实例名称
        defaultMQPushConsumer.setInstanceName(MqTopicAndTagConstants.MQTT_PROCESS_PLS_INSTANCE_NAME);
    }
}
